<template>
  <div class="edit-channel">
    <van-cell title="我的频道">
      <van-button type="default" size="mini" round @click="isEdit = !isEdit"> {{ isEdit ? '完成' :'编辑'  }} </van-button>
    </van-cell>
    <van-grid :gutter="12">
      <van-grid-item @click="editChannelClick(item,index)" :class="index === active ? 'active':'' " :text="v.name" v-for="(v,index) in UserChannel" :key="index">
        <van-icon v-show="isEdit && index !==0 " slot="icon" name="clear" />
      </van-grid-item>
    </van-grid>
    <van-cell title="推荐频道">
    </van-cell>
    <van-grid :gutter="12">
      <van-grid-item :text="v.name" v-for="(v,index) in remmonedChannel" @click='addChannel(v)' :key="index">
      </van-grid-item>
    </van-grid>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { getAllChannels } from '@/api/channel.js'
import { setItem } from '@/utils/storage'
export default {
  name: 'editChannle',
  props: {
    UserActive: {
      type: Number,
      ruquired: true
    },
    UserChannel: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      isEdit: false,
      allChannel: [],
      active: this.UserActive
    }
  },
  created() {
    this.loadAllChannel()
  },
  methods: {
    async loadAllChannel() {
      const { data: res } = await getAllChannels()
      this.allChannel = res.data.channels
    },
    addChannel(item) {
      if (this.isEdit) {
        this.UserChannel.push(item)
      }
      setItem('user-channel', this.UserChannel)
    },
    editChannelClick(item, index) {
      if (this.isEdit) {
        this.delete(index)
      } else {
        this.switch(index)
      }
    },
    delete(index) {
      if (index === 0) {
        return this.$toast({ message: '不能删除' })
      } else if (index <= this.active) {
        this.$emit('update-active', this.active--)
      }
      this.UserChannel.splice(index, 1)
      setItem('user-channel', this.UserChannel)
    },
    switch(index) {
      if (this.isEdit) {
        return null
      } else {
        this.active = index
        this.$emit('update-active', this.active)
        this.$emit('close')
      }
    }
  },
  computed: {
    ...mapState(['user']),
    remmonedChannel() {
      return this.allChannel.filter(item => {
        return !this.UserChannel.find(channel => {
          return channel.id === item.id
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.edit-channel {
  margin-top: 50px;
  height: 100%;
  width: 100%;
  .van-button {
    width: 50px;
  }
}
.van-grid-item {
  // position: relative;
  height: 40px;

  /deep/.van-grid-item__content {
    background-color: #eee;
  }
  .van-icon-clear {
    position: absolute;
    right: -42px;
    top: -15px;
    font-size: 12px;
    z-index: 30;
  }
}
.active /deep/ .van-grid-item__text {
  color: chocolate;
}
</style>
